var wechat = require('wechat');
var express = require('express');
var request = require('request');
var router = express.Router();
var log = require('../logger.js');
var dbDao=require('../models/dbBase.js');
var settings = require('../settings');



var config = {
    token: 'b69sa31acb9d74ce52v8a6824d64c009',
    appid: settings.appid,
    encodingAESKey: 'iNKQbUFPNODZ1IueeYZEmpJxP9dI813QR57NOGdacvF'
};

/**
 * 关注微信号后进入微信号触发的地址;此地址接受微信发来的消息;
 * 分三种情况:
 * 新用户第一次关注进入
 * 老用户进入;
 */
router.post('/m/wx', wechat(config, function(req, res, next){
    var message = req.weixin;
    console.log('--/m/wx---',message);
    var openid = message.FromUserName;
    if( message.MsgType ==="event" && message.Event === "subscribe" ){
        console.log("用户关注进入")
        var sql="select * from members where wxopenId='"+openid+"'";
        dbDao.find(sql,function(err,result){
            if(result.length>0){
                var sql2="update members set status=? where wxopenId=?";
                var params=['已关注',openid];
                dbDao.querys(sql2,params,function(err,result){
                    if(result.resultCode=='0'){
                        console.log('修改成功,已经关注');
                    }else{
                        console.log('修改失败,');
                    }
                    res.reply([
                        {
                            title: '欢迎进入去场馆公众号',
                            description: '欢迎关注我们，去场馆，给您不一样的体验',
                            picurl: 'https://mmbiz.qlogo.cn/mmbiz_jpg/sesM1oMBuBjiamFryqzbUxf2ZKNnM4IrQr7o0RqqvoX6kKf9GYQJ0zAufXJB7LPSV8nky78ZudVQhcke9zQLBHw/0?wx_fmt=jpeg',
                            url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + settings.appid + '&redirect_uri=http%3a%2f%2fgo.sportscv.cn&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
                        }
                    ]);
                });
            }else{
                console.log("新用户");//这个时候还不能getUser?

                res.reply([
                    {
                        title: '欢迎进入去场馆公众号',
                        description: '欢迎关注我们，去场馆，给您不一样的体验',
                        picurl: 'https://mmbiz.qlogo.cn/mmbiz_jpg/sesM1oMBuBjiamFryqzbUxf2ZKNnM4IrQr7o0RqqvoX6kKf9GYQJ0zAufXJB7LPSV8nky78ZudVQhcke9zQLBHw/0?wx_fmt=jpeg',
                        url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + settings.appid + '&redirect_uri=http%3a%2f%2fgo.sportscv.cn&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
                    }
                ]);
            }
        })
    }else if( message.MsgType ==="event" && message.Event === "LOCATION" ) {
        /*这里位置增加当已经insert过的会失败,应该是执行update---jstong*/
        var sql1="select * from members where wxopenId='"+openid+"'";
        dbDao.find(sql1,function(err,result){
            if(result.length>0) {
                var sql2 = "update members set status=? where wxopenId=?";
                var params = ['已关注', openid];
                dbDao.querys( sql2, params, function (err, result) {
                    if (result.resultCode == '0') {
                        console.log('老用户登录成功');
                        var params = [
                            message.FromUserName,'微信',message.Longitude,message.Latitude,new Date().format('yyyy-MM-dd hh:mm:ss')
                        ];
                        var sql="insert into memberPosition(openId,loginType,longitude,latitude,loginTime) values(?,?,?,?,?)";
                        dbDao.querys(params,function(err,result){
                            if(result.resultCode=='0'){
                                console.log('添加地理位置成功');
                            }else{
                                console.log('添加地理位置失败');
                            }
                            res.reply([]);
                        });

                    } else {
                        console.log('老用户登录报错');
                        res.reply()
                    }
                });
            }else{
                console.log("未查询到老用户");
                res.reply()
            }
        });
        //上传地理信息更新用户信息,通过apenId获取用户信息,然后更新用户信息;
    }else if( message.MsgType ==="event" && message.Event === "unsubscribe" ) {

        //用户取消关注,修改数据库中用户状态改为 取消关注状态
        console.log("用户取消关注");
        var sql="select * from members where wxopenId='"+openid+"'";
        dbDao.find(sql,function(err,result){
            if(result.length>0){
                var sql2="update members set status=? where wxopenId=?";
                var params=['未关注',openid];
                dbDao.querys(sql2,params,function(err,result){
                    if(result.resultCode=='0'){
                        console.log('修改成功');
                    }else{
                        log.logger.info('修改失败');
                    }
                    res.reply([]);
                });
            }else{
                console.log("取消关注时未查到用户");
            }
        });

    }else if( message.MsgType ==="text") {
        console.log("用户发送文本消息");
        res.reply( '欢迎进入华亿创新公众号');
    }
}));



//// 点击订单查询生成 此时的链接;
//router.get('/clm1', function (req, res, next) {
//    var domain = "http://go.sportscv.cn";
//    var auth_callback_url = domain + "/oauth/callback"
//    var url = global.oauth_client.getAuthorizeURL(auth_callback_url, '', 'snsapi_userinfo');
//    console.log(url);
//    // 重定向请求到微信服务器
//    res.redirect(url);
//});
//
//router.get('/oauth/callback', function (req, res, next) {
//    console.log('/oauth/callback');
//    var code = req.query.code;
//    global.oauth_client.getAccessToken(code, function (err, result) {
//        if(err){
//            res.json({err:'code error'});
//        }else{
//            console.log(result)
//            var accessToken = result.data.access_token;
//            var openid = result.data.openid;
//
//            global.oauth_client.getUser(openid, function (err, result) {
//                var userInfo = result;
//                // save or other opration
//                res.json(userInfo)
//            });
//        }
//
//    });
//});

module.exports = router;



